"""
FastAPI 主应用
"""
from pathlib import Path
from dotenv import load_dotenv
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# 加载环境变量
env_path = Path(__file__).parent / '.env'
if env_path.exists():
    load_dotenv(env_path)

from database import init_db
from api.experiment_templates import router as template_router
from api.workflows import router as workflow_router
from api.workflow_templates import router as workflow_template_router  # 新增
from api.workflow_instances_ext import router as workflow_instance_ext_router  # 新增
from api.monitoring import router as monitoring_router
from api.roma_pools import router as roma_pool_router
from api.config_presets import router as config_preset_router
from api.applications import router as application_router

# 创建 FastAPI 应用
app = FastAPI(
    title="BMC实验管理平台 API",
    description="实验模板管理和工作流编排平台",
    version="2.0.0",  # 版本号升级
    docs_url="/api/docs",
    redoc_url="/api/redoc"
)

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(template_router)
app.include_router(workflow_router)  # 保留兼容性
app.include_router(workflow_template_router)  # 新增：工作流模板管理
app.include_router(workflow_instance_ext_router)  # 新增：工作流实例扩展
app.include_router(monitoring_router)
app.include_router(roma_pool_router)
app.include_router(application_router)  # 应用管理
app.include_router(config_preset_router)


@app.on_event("startup")
def on_startup():
    """应用启动时初始化数据库和调度器"""
    init_db()

    # 启动定时调度服务
    from services.scheduler_service import scheduler_service
    scheduler_service.start()
    scheduler_service.load_all_workflows()  # 加载工作流级别的定时任务（兼容旧版）
    scheduler_service.load_all_instances()  # 加载实例级别的定时任务（新增）


@app.on_event("shutdown")
def on_shutdown():
    """应用关闭时清理资源"""
    from services.scheduler_service import scheduler_service
    scheduler_service.shutdown()


@app.get("/")
def read_root():
    """根路径"""
    return {
        "message": "欢迎使用 BMC实验管理平台 API",
        "docs": "/api/docs",
        "version": "1.0.0"
    }


@app.get("/health")
def health_check():
    """健康检查"""
    return {"status": "healthy"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
